﻿Public Class OfflineRecordset : Inherits Recordset

	Dim LocalFolder = My.Computer.FileSystem.SpecialDirectories.Temp & "\"
	Dim RemoteFolder = ""
	Dim FileName As String

	Sub New(ByVal RemoteFolder As String, ByVal FileName As String, ByVal Fields As String)
		MyBase.New(Fields)
		Me.RemoteFolder = RemoteFolder
		Me.FileName = FileName
	End Sub

	Dim RemoteVersion As Integer = 0
	Dim LocalVersion As Integer = 0

	Sub Open()
		RemoteVersion = GetVersion(RemoteFolder, FileName)
		LocalVersion = GetVersion(LocalFolder, FileName)
		If LocalVersion < RemoteVersion Then
			My.Computer.FileSystem.CopyFile(RemoteFolder & FileName & "." & RemoteVersion, LocalFolder & FileName & "." & RemoteVersion)
			LocalVersion = RemoteVersion
		End If
		If LocalVersion > 0 Then Import(LocalFolder & FileName & "." & LocalVersion)
	End Sub

	Function GetVersion(ByVal Folder As String, ByVal File As String) As Integer
		Dim Files = My.Computer.FileSystem.GetFiles(Folder, FileIO.SearchOption.SearchTopLevelOnly, File & ".*")
		If Files.Count = 0 Then Return 0
		Return (From f In Files Select Val(Mid(f, InStrRev(f, ".") + 1))).Max
	End Function

	ReadOnly Property IsEmpty As Boolean
		Get
			Return Rows.Count = 0
		End Get
	End Property

	Overloads Sub Save()
		LocalVersion += 1
		Export(LocalFolder & FileName & "." & LocalVersion)
		If LocalVersion > 10 Then
			For i = 1 To 2
				Dim ObsoleteFile = Choose(i, LocalFolder, RemoteFolder) & FileName & "." & (LocalVersion - 10)
				If My.Computer.FileSystem.FileExists(ObsoleteFile) Then My.Computer.FileSystem.DeleteFile(ObsoleteFile)
			Next
		End If
		If Not AsyncSave.IsBusy Then AsyncSave.RunWorkerAsync()
	End Sub

	Dim WithEvents AsyncSave As New System.ComponentModel.BackgroundWorker

	Private Sub AsyncSave_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles AsyncSave.DoWork
		My.Computer.FileSystem.CopyFile(LocalFolder & FileName & "." & LocalVersion, RemoteFolder & FileName & "." & LocalVersion)
	End Sub

	Private Sub AsyncSave_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles AsyncSave.RunWorkerCompleted
		RemoteVersion = LocalVersion
	End Sub

End Class